package com.software.levelupandroid.mine.view;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Result;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.taskIssue.view.activity.TaskIssueActivity;
import com.software.levelupandroid.utils.FileUtil;
import com.software.levelupandroid.utils.StringUtil;
import com.software.levelupandroid.utils.ToastUtil;
import com.software.levelupandroid.utils.TokenUtil;
import com.software.levelupandroid.utils.UserUtil;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class EditUserActivity extends AppCompatActivity {
    private EditText nameEdit,emailEdit,sexEdit,signatureEdit;
    private TextView idTextView;
    private ImageView avatar;
    private Toolbar toolbarUser;
    private User user;
    private PopupWindow pop;
    private String imagePath;
    private String updateUserServerPath;
    private OkHttpClient okHttpClient;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user);
        initToolbar();
        findViews();
        initData();
        setListener();
    }

    private void setListener() {
        avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPop();
            }
        });
    }

    private void initToolbar() {
        toolbarUser = findViewById(R.id.toolbar_user);
        setSupportActionBar(toolbarUser);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
            actionBar.setDisplayShowTitleEnabled(false);
        if (toolbarUser != null){
            toolbarUser.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }

    }

    /**
     * ”向上“按钮的点击事件
     * @return
     */
    @Override
    public boolean onSupportNavigateUp() {
        finish();
//        onBackPressed();
        return true;
    }

    /**
     * 加载toolbar上的菜单资源
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_confirm_menu,menu);
        return true;
    }

    /**
     * 设置菜单项中的点击事件（删除按钮的点击事件）
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_confirm:
                updateUser();
                break;
        }
        return true;
    }

    private void updateUser() {
        System.out.println("更新用户");
        User user = UserUtil.getUser(EditUserActivity.this);
        user.setEmail(emailEdit.getText().toString());
        user.setUsername(nameEdit.getText().toString());
        user.setSex(sexEdit.getText().toString());
        user.setSignature(signatureEdit.getText().toString());
        String userJson = new Gson().toJson(user);
        RequestBody userBody = RequestBody.create(
                MediaType.parse("application/json;charset=UTF-8"),
                userJson
        );
        RequestBody requestBody = null;
        // 如果更新中包括用户头像
        if (StringUtil.isNotEmpty(imagePath)){
            File file = new File(imagePath);
            byte[] fileData = FileUtil.fileToStream(file);
            RequestBody fileBody = RequestBody.create(
                    MediaType.parse("image/jpeg"),
                    fileData
            );
            requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("user", null, userBody)
                    .addFormDataPart("avatar", file.getName(), fileBody)
                    .build();
        }else {
            requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("user",null,userBody)
                    .build();
        }
        String token = TokenUtil.getToken(EditUserActivity.this);
        Request request = new Request.Builder()
                .header("Authorization","level-up " + token)
                .post(requestBody)
                .url(updateUserServerPath)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtil.showToastOnUI(EditUserActivity.this,"修改失败");
                Log.e("editUser:",e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String respJson = response.body().string();
                System.out.println("editUser:" + respJson);
                Type userType = new TypeToken<Result<User>>(){}.getType();
                Result<User> result = new Gson().fromJson(respJson, userType);
                if (result != null){
                    if (result.getCode() != null && result.getCode().equals("200")){
                        User user1 = result.getData();
                        UserUtil.saveUser(user1,EditUserActivity.this);
                        ToastUtil.showToastOnUI(EditUserActivity.this, "修改成功");
                    }
                }
            }
        });
    }



    private void findViews() {
        nameEdit = findViewById(R.id.name_edit);
        emailEdit = findViewById(R.id.email_edit);
        sexEdit = findViewById(R.id.sex_edit);
        signatureEdit = findViewById(R.id.signature_edit);
        idTextView = findViewById(R.id.id);
        avatar = findViewById(R.id.avatar);
    }

    private void initData(){
        okHttpClient = new OkHttpClient();
        updateUserServerPath = getApplicationContext().getString(R.string.updateUserServerPath);
        user = UserUtil.getUser(this);
        nameEdit.setText(user.getUsername());
        emailEdit.setText(user.getEmail());
        sexEdit.setText(user.getSex());
        signatureEdit.setText(user.getSignature());
        idTextView.setText("ID: "+user.getUserId());
        System.out.println(user.getAvatar());
        Glide.with(this)
                .load(user.getAvatar())
                .into(avatar);
    }

    private void showPop() {
        View bottomView = View.inflate(EditUserActivity.this, R.layout.layout_bottom_dialog,null);
        TextView mAlbum = bottomView.findViewById(R.id.tv_album);
        TextView mCamera = bottomView.findViewById(R.id.tv_camera);
        TextView mCancel = bottomView.findViewById(R.id.tv_cancel);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.tv_album:
                        //相册
                        PictureSelector.create(EditUserActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(1)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_camera:
                        //相机
                        PictureSelector.create(EditUserActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_cancel:
                        break;
                }
                closePopupWindow();
            }
        };
        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }

    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 操作
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> images = PictureSelector.obtainMultipleResult(data);
                    LocalMedia media = images.get(0);
                    imagePath = media.getPath();
                    Glide.with(EditUserActivity.this)
                            .load(media.getPath())
                            .into(avatar);
                    System.out.println(imagePath);
                    break;
            }
        }
    }



}